package com.net.lnk.rpc.http.invoke;

import java.util.concurrent.TimeUnit;

import com.net.lnk.rpc.http.exception.RpcException;
import com.net.lnk.rpc.http.exception.RpcExceptionEnum;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * HTTP 调用客户端
 */
public class HttpInvoker implements Invoker {

	public static final Invoker invoker = new HttpInvoker();

	private final OkHttpClient httpClient = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS)
			.writeTimeout(5, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS).build();

	public String invoke(String request, ConsumerConfig consumerConfig) throws RpcException {

		okhttp3.RequestBody body = new FormBody.Builder().add("requestBody", request).build();
		Request okReq = new Request.Builder().url(consumerConfig.getUrl()).post(body).build();
		try {
			Response okResp = httpClient.newCall(okReq).execute();
			if (okResp.isSuccessful()) {
				return okResp.body().string();
			} else {
				throw new RpcException(RpcExceptionEnum.INVOKE_ERROR.getCode(), request);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RpcException(RpcExceptionEnum.INVOKE_ERROR.getCode(), request);
		}
	}

}
